<template>
  <div class="overflow-hidden">
    <!-- 表格容器 -->
    <div class="overflow-x-auto">
      <table class="min-w-full divide-y divide-gray-200">
        <!-- 表头 -->
        <thead class="bg-gray-50">
          <tr>
            <th
              v-for="column in columns"
              :key="column.key"
              :style="{ width: column.width }"
              class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
              :class="{ 'cursor-pointer hover:bg-gray-100': column.sortable }"
              @click="column.sortable && handleSort(column.key)"
            >
              <div class="flex items-center space-x-1">
                <span>{{ column.title }}</span>
                <div v-if="column.sortable" class="flex flex-col">
                  <i
                    :class="[
                      'w-3 h-3 mdi:chevron-up',
                      sortField === column.key && sortOrder === 'asc'
                        ? 'text-blue-600'
                        : 'text-gray-400'
                    ]"
                  />
                  <i
                    :class="[
                      'w-3 h-3 mdi:chevron-down -mt-1',
                      sortField === column.key && sortOrder === 'desc'
                        ? 'text-blue-600'
                        : 'text-gray-400'
                    ]"
                  />
                </div>
              </div>
            </th>
          </tr>
        </thead>

        <!-- 表体 -->
        <tbody class="bg-white divide-y divide-gray-200">
          <!-- 加载状态 -->
          <tr v-if="loading">
            <td :colspan="columns.length" class="px-6 py-12 text-center">
              <div class="flex items-center justify-center">
                <i class="w-6 h-6 mr-2 animate-spin text-blue-600 mdi:loading" />
                <span class="text-gray-500">加载中...</span>
              </div>
            </td>
          </tr>

          <!-- 空数据状态 -->
          <tr v-else-if="sortedData.length === 0">
            <td :colspan="columns.length" class="px-6 py-12 text-center">
              <div class="flex flex-col items-center">
                <i class="w-12 h-12 text-gray-400 mdi:database-off" />
                <p class="mt-2 text-sm text-gray-500">暂无数据</p>
              </div>
            </td>
          </tr>

          <!-- 数据行 -->
          <tr
            v-else
            v-for="(row, index) in paginatedData"
            :key="getRowKey(row, index)"
            class="hover:bg-gray-50 transition-colors duration-150"
          >
            <td
              v-for="column in columns"
              :key="column.key"
              class="px-6 py-4 whitespace-nowrap"
              :class="getCellClass(column)"
            >
              <!-- 操作列 -->
              <div v-if="column.key === 'actions'" class="flex items-center space-x-2">
                <button
                  v-if="!hideActions.includes('view')"
                  @click="$emit('view', row)"
                  class="text-blue-600 hover:text-blue-900 transition-colors"
                  title="查看"
                >
                  <i class="w-4 h-4 mdi:eye" />
                </button>
                <button
                  v-if="!hideActions.includes('edit')"
                  @click="$emit('edit', row)"
                  class="text-green-600 hover:text-green-900 transition-colors"
                  title="编辑"
                >
                  <i class="w-4 h-4 mdi:pencil" />
                </button>
                <button
                  v-if="!hideActions.includes('delete')"
                  @click="$emit('delete', row)"
                  class="text-red-600 hover:text-red-900 transition-colors"
                  title="删除"
                >
                  <i class="w-4 h-4 mdi:delete" />
                </button>
              </div>

              <!-- 自定义插槽 -->
              <slot
                v-else-if="$slots[column.key]"
                :name="column.key"
                :row="row"
                :value="getNestedValue(row, column.key)"
                :index="index"
              />

              <!-- 默认内容 -->
              <span v-else class="text-sm text-gray-900">
                {{ getNestedValue(row, column.key) }}
              </span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div
      v-if="!loading && sortedData.length > 0 && pagination"
      class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6"
    >
      <div class="flex-1 flex justify-between sm:hidden">
        <button
          @click="previousPage"
          :disabled="currentPage === 1"
          class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          上一页
        </button>
        <button
          @click="nextPage"
          :disabled="currentPage === totalPages"
          class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          下一页
        </button>
      </div>

      <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
        <div>
          <p class="text-sm text-gray-700">
            显示第
            <span class="font-medium">{{ startIndex }}</span>
            到
            <span class="font-medium">{{ endIndex }}</span>
            条，共
            <span class="font-medium">{{ sortedData.length }}</span>
            条记录
          </p>
        </div>

        <div class="flex items-center space-x-2">
          <!-- 每页显示数量选择 -->
          <div class="flex items-center space-x-2">
            <span class="text-sm text-gray-700">每页显示</span>
            <select
              v-model="pageSize"
              class="border border-gray-300 rounded-md text-sm px-2 py-1 focus:ring-blue-500 focus:border-blue-500"
            >
              <option v-for="size in pageSizeOptions" :key="size" :value="size">
                {{ size }}
              </option>
            </select>
            <span class="text-sm text-gray-700">条</span>
          </div>

          <!-- 页码导航 -->
          <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
            <button
              @click="previousPage"
              :disabled="currentPage === 1"
              class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <i class="w-4 h-4 mdi:chevron-left" />
            </button>

            <button
              v-for="page in visiblePages"
              :key="page"
              @click="goToPage(page)"
              :class="[
                'relative inline-flex items-center px-4 py-2 border text-sm font-medium',
                page === currentPage
                  ? 'z-10 bg-blue-50 border-blue-500 text-blue-600'
                  : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'
              ]"
            >
              {{ page }}
            </button>

            <button
              @click="nextPage"
              :disabled="currentPage === totalPages"
              class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <i class="w-4 h-4 mdi:chevron-right" />
            </button>
          </nav>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'

interface Column {
  key: string
  title: string
  width?: string
  sortable?: boolean
  align?: 'left' | 'center' | 'right'
}

interface Props {
  columns: Column[]
  data: any[]
  loading?: boolean
  pagination?: boolean
  pageSize?: number
  hideActions?: string[]
  rowKey?: string
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  pagination: true,
  pageSize: 10,
  hideActions: () => [],
  rowKey: 'id'
})

const emit = defineEmits<{
  view: [row: any]
  edit: [row: any]
  delete: [row: any]
}>()

// 排序状态
const sortField = ref<string>('')
const sortOrder = ref<'asc' | 'desc'>('asc')

// 分页状态
const currentPage = ref(1)
const pageSize = ref(props.pageSize)
const pageSizeOptions = [10, 20, 50, 100]

// 获取嵌套对象的值
const getNestedValue = (obj: any, path: string) => {
  return path.split('.').reduce((current, key) => current?.[key], obj)
}

// 获取行的唯一键
const getRowKey = (row: any, index: number) => {
  return getNestedValue(row, props.rowKey) || index
}

// 获取单元格样式类
const getCellClass = (column: Column) => {
  const alignClass = {
    left: 'text-left',
    center: 'text-center',
    right: 'text-right'
  }
  return alignClass[column.align || 'left']
}

// 排序后的数据
const sortedData = computed(() => {
  if (!sortField.value) {
    return props.data
  }

  return [...props.data].sort((a, b) => {
    const aValue = getNestedValue(a, sortField.value)
    const bValue = getNestedValue(b, sortField.value)

    let result = 0
    if (aValue < bValue) result = -1
    else if (aValue > bValue) result = 1

    return sortOrder.value === 'desc' ? -result : result
  })
})

// 分页后的数据
const paginatedData = computed(() => {
  if (!props.pagination) {
    return sortedData.value
  }

  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return sortedData.value.slice(start, end)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(sortedData.value.length / pageSize.value)
})

// 当前页显示的数据范围
const startIndex = computed(() => {
  return (currentPage.value - 1) * pageSize.value + 1
})

const endIndex = computed(() => {
  return Math.min(currentPage.value * pageSize.value, sortedData.value.length)
})

// 可见的页码
const visiblePages = computed(() => {
  const pages = []
  const total = totalPages.value
  const current = currentPage.value

  if (total <= 7) {
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    if (current <= 4) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      pages.push(1)
      pages.push('...')
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      pages.push(1)
      pages.push('...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }

  return pages
})

// 处理排序
const handleSort = (field: string) => {
  if (sortField.value === field) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortField.value = field
    sortOrder.value = 'asc'
  }
}

// 分页操作
const goToPage = (page: number | string) => {
  if (typeof page === 'number' && page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

const previousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

// 监听页面大小变化，重置到第一页
watch(pageSize, () => {
  currentPage.value = 1
})

// 监听数据变化，重置到第一页
watch(() => props.data, () => {
  currentPage.value = 1
})
</script>